<template>
	<el-form ref="formRef" :model="ruleForm" :rules="rules" class="login-content-form" size="large">
		<el-form-item prop="accountType">
			<el-select v-model="ruleForm.accountType" class="w100">
				<el-option label="平台端" :value="1" />
				<el-option label="供应商端" :value="0" />
			</el-select>
		</el-form-item>
		<el-form-item prop="username">
			<el-input
				type="text"
				:placeholder="$t('message.account.accountPlaceholder1')"
				prefix-icon="el-icon-user"
				v-model="ruleForm.username"
				clearable
				autocomplete="off"
			>
			</el-input>
		</el-form-item>
		<el-form-item prop="password">
			<el-input
				:type="isShowPassword ? 'text' : 'password'"
				:placeholder="$t('message.account.accountPlaceholder2')"
				prefix-icon="el-icon-lock"
				v-model="ruleForm.password"
				autocomplete="off"
			>
				<template #suffix>
					<i
						class="iconfont el-input__icon login-content-password"
						:class="isShowPassword ? 'icon-yincangmima' : 'icon-xianshimima'"
						@click="isShowPassword = !isShowPassword"
					>
					</i>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item prop="code">
			<el-row :gutter="15">
				<el-col :span="16">
					<el-input
						type="text"
						maxlength="4"
						:placeholder="$t('message.account.accountPlaceholder3')"
						prefix-icon="el-icon-position"
						v-model="ruleForm.code"
						clearable
						autocomplete="off"
					></el-input>
				</el-col>
				<el-col :span="8">
					<div @click="onCodeRandom" class="login-content-code">
						<span class="login-content-code-img">{{ codeRandom }}</span>
					</div>
				</el-col>
			</el-row>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" class="login-content-submit" round @click="onSignIn" :loading="loading.signIn">
				<span>{{ $t('message.account.accountBtnText') }}</span>
			</el-button>
		</el-form-item>
	</el-form>
</template>

<script lang="ts">
import { computed, defineComponent, getCurrentInstance, reactive, ref, toRefs } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';

import { login } from '/@/api/admin1';
import { supplier1Api } from '/@/api/admin';
import { initFrontEndControlRoutes } from '/@/router/frontEnd';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { useStore } from '/@/store/index';
import { Session } from '/@/utils/storage';
import { formatAxis } from '/@/utils/formatTime';
import { randomString } from '/@/utils/utils';

const Supplier1Api = supplier1Api();
export default defineComponent({
	name: 'loginAccount',
	setup() {
		const { proxy } = getCurrentInstance() as any;
		const state = reactive({
			isShowPassword: false,
			ruleForm: {
				accountType: 1,
				username: '',
				password: '',
				code: '',
			},
			rules: {
				username: [{ required: true, trigger: 'blur', message: '用户名不能为空' }],
				password: [{ required: true, trigger: 'blur', message: '密码不能为空' }],
				code: [{ required: true, trigger: 'blur', message: '验证码不能为空' }],
			},
			codeRandom: randomString(4),
			loading: {
				signIn: false,
			},
		});

		const formRef = ref(null);
		const store = useStore();
		const route: any = useRoute();
		const router = useRouter();
		const { t } = useI18n();

		// 时间获取
		const currentTime = computed(() => {
			return formatAxis(new Date());
		});
		// 生成随机验证码
		const onCodeRandom = () => {
			state.codeRandom = randomString(4);
		};
		// 登录
		const onSignIn = async () => {
			(formRef.value as any)?.validate((valid: boolean) => {
				if (valid) {
					if (state.ruleForm.code.toLowerCase() != state.codeRandom.toLowerCase()) {
						ElMessage.error('请输入正确的验证码');
						return true;
					}
					state.loading.signIn = true;
					if (state.ruleForm.accountType) {
						_login(state.ruleForm);
					} else {
						_login1(state.ruleForm);
					}
				}
			});
		};
		// 登录成功后的跳转
		const signInSuccess = () => {
			// 初始化登录成功时间问候语
			let currentTimeInfo = currentTime.value;
			// 登录成功，跳到转首页
			// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
			// 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
			if (route.query?.redirect) {
				router.push({
					path: route.query?.redirect,
					query: Object.keys(route.query?.params).length > 0 ? JSON.parse(route.query?.params) : '',
				});
			} else {
				router.push('/');
			}
			// 登录成功提示
			setTimeout(() => {
				// 关闭 loading
				state.loading.signIn = true;
				const signInText = t('message.signInText');
				ElMessage.success(`${currentTimeInfo}，${signInText}`);
				// 修复防止退出登录再进入界面时，需要刷新样式才生效的问题，初始化布局样式等(登录的时候触发，目前方案)
				location.reload();
				proxy.mittBus.emit('onSignInClick');
			}, 300);
		};

		/********** 网络事件 **********/
		// 登录
		const _login = (_data: object) => {
			login(_data)
				.then(async (res: any) => {
					console.log('登录', res);
					state.loading.signIn = false;
					let defaultAuthPageList: Array<string> = [];
					let defaultAuthBtnList: Array<string> = [];
					if (res.data.info.username === 'admin') {
						defaultAuthPageList = [
							'1',
							'2',
							'21',
							'22',
							'23',
							'3',
							'31',
							'32',
							'33',
							// '34',
							'4',
							'41',
							'42',
							'43',
							'5',
							'51',
							'52',
							'53',
							'54',
							'6',
							'7',
							'71',
							'73',
							'74',
							'8',
							'81',
							'82',
							'83',
							'84',
							'9',
							'91',
							'92',
							'93',
							'94',
							'95',
							'96',
						];
					} else {
						defaultAuthPageList = JSON.parse(res.data.info.menu).map((item: any) => String(item));
					}
					// 用户信息模拟数据
					const userInfos = {
						userName: res.data.info.username,
						nickname: res.data.info.nickname,
						is_supplier: 0,
						menu: res.data.info.menu,
						photo: res.data.info.avatar ? import.meta.env.VITE_FILE_API + res.data.info.avatar : import.meta.env.VITE_FILE_API + '/hbsk_cloud/material/logo.jpg',
						time: new Date().getTime(),
						authPageList: defaultAuthPageList,
						authBtnList: defaultAuthBtnList,
					};
					// 存储 token 到浏览器缓存
					Session.set('token', res.data.token);
					// 存储用户信息到浏览器缓存
					Session.set('userInfo', userInfos);
					// 1、请注意执行顺序(存储用户信息到vuex)
					store.dispatch('userInfos/setUserInfos', userInfos);
					if (!store.state.themeConfig.themeConfig.isRequestRoutes) {
						// 前端控制路由，2、请注意执行顺序
						await initFrontEndControlRoutes();
						signInSuccess();
					} else {
						// 模拟后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
						// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
						await initBackEndControlRoutes();
						// 执行完 initBackEndControlRoutes，再执行 signInSuccess
						signInSuccess();
					}
					// ElMessage.success('添加成功！');
				})
				.catch(() => {
					state.loading.signIn = false;
				});
		};
		// 供应商登录
		const _login1 = (_data: object) => {
			Supplier1Api.login(_data)
				.then(async (res: any) => {
					console.log('登录', res);
					state.loading.signIn = false;
					let defaultAuthPageList: Array<string> = ['1','7','71','72'];
					let defaultAuthBtnList: Array<string> = [];
					// 用户信息模拟数据
					const userInfos = {
						userName: res.data.info.username,
						nickname: res.data.info.title,
						is_supplier: 1,
						menu: res.data.info.menu,
						photo: res.data.info.avatar ? import.meta.env.VITE_FILE_API + res.data.info.avatar : import.meta.env.VITE_FILE_API + '/hbsk_cloud/material/logo.jpg',
						time: new Date().getTime(),
						authPageList: defaultAuthPageList,
						authBtnList: defaultAuthBtnList,
					};
					// 存储 token 到浏览器缓存
					Session.set('token', res.data.token);
					// 存储用户信息到浏览器缓存
					Session.set('userInfo', userInfos);
					// 1、请注意执行顺序(存储用户信息到vuex)
					store.dispatch('userInfos/setUserInfos', userInfos);
					if (!store.state.themeConfig.themeConfig.isRequestRoutes) {
						// 前端控制路由，2、请注意执行顺序
						await initFrontEndControlRoutes();
						signInSuccess();
					} else {
						// 模拟后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
						// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
						await initBackEndControlRoutes();
						// 执行完 initBackEndControlRoutes，再执行 signInSuccess
						signInSuccess();
					}
					// ElMessage.success('添加成功！');
				})
				.catch(() => {
					state.loading.signIn = false;
				});
		};

		return {
			formRef,
			currentTime,
			onCodeRandom,
			onSignIn,
			...toRefs(state),
		};
	},
});
</script>

<style scoped lang="scss">
.login-content-form {
	margin-top: 10px;

	.login-content-password {
		display: inline-block;
		width: 25px;
		cursor: pointer;

		&:hover {
			color: #909399;
		}
	}

	.login-content-code {
		display: flex;
		align-items: center;
		justify-content: space-around;

		.login-content-code-img {
			width: 100%;
			height: 40px;
			line-height: 40px;
			background-color: #ffffff;
			border: 1px solid rgb(220, 223, 230);
			color: #333;
			font-size: 16px;
			font-weight: 700;
			letter-spacing: 5px;
			text-indent: 5px;
			text-align: center;
			cursor: pointer;
			transition: all ease 0.2s;
			border-radius: 4px;
			user-select: none;

			&:hover {
				border-color: #c0c4cc;
				transition: all ease 0.2s;
			}
		}
	}

	.login-content-submit {
		width: 100%;
		letter-spacing: 2px;
		font-weight: 300;
	}
}
</style>
